//
//  ExportExcelPage.swift
//  ReportScan
//
//  Created by woniu on 2025/7/25.
//

import SwiftUI
import SwiftXLSX

struct ExportExcelPage: View {
    
    @State var pageIndex = 0
    @State var errorPage:Set<Int> = []
    @State var dataMap:[Int:[UserItem]] = [:]
    @State var tableHeaderNames:Set<String> = []
    @State var totalCount = 0
    @State var isStop = false
    var body: some View {
        Text("根据数据生成excel表格，并导出")
        VStack(alignment: .leading) {
            Button(role: .none) {
                genderExcel()
            } label: {
                Text("导出")
            }
            Button(role: .none) {
                self.onWillDown()
            } label: {
                Text("获取数据")
            }
            Button(role: .none) {
                isStop = true
            } label: {
                Text("暂停")
            }
            Button(role: .none) {
                isStop = false
                onWillDown()
            } label: {
                Text("继续")
            }
            
            Button(role: .none) {
                print(self.errorPage)
            } label: {
                Text("错误页")
            }
        }
        .padding()
        Spacer()
    }
    ///注入档案数据
    private func genderExcel() {
        
        var userList:[UserItem] = []
        for subArr in self.dataMap.values{
            userList.append(contentsOf: subArr)
        }
        
        let excelBook = XWorkBook()
        
        func GetRandomFont() -> XFontName {
            let cases = XFontName.allCases
            return cases[Int.random(in: 0..<cases.count)]
        }
        let sheet = excelBook.NewSheet("档案质控")
        
        //姓名
        let nameCell = sheet.AddCell(XCoords(row: 1, col: 1))
        nameCell.value = .text("姓名")
        
        //身份证
        let idCardCell = sheet.AddCell(XCoords(row: 1, col: 2))
        idCardCell.value = .text("身份证")
        
        //其他动态字段
        let headerOthers = getTableHealer()
        for (otherIndex,groupName) in headerOthers.enumerated(){
            let remarkCell = sheet.AddCell(XCoords(row: 1, col: 3+otherIndex))
            remarkCell.value = .text(groupName)
        }
       
        //内容
        for (index,user) in userList.enumerated(){
            let row = index + 2
            //姓名
            let itemCell1 = sheet.AddCell(XCoords(row:row, col: 1))
            itemCell1.value = .text(user.rhrName)
            
            //身份证
            let itemCell2 = sheet.AddCell(XCoords(row:row, col: 2))
            itemCell2.value = .text(user.rhrIdCard.toIdCardHidden())
            
            //其他字段
            for (otherIndex,groupName) in headerOthers.enumerated(){
                let itemCell = sheet.AddCell(XCoords(row:row, col: 3+otherIndex))
                let groupNameDic = user.getGroupMap()
                let msg = groupNameDic[groupName] ?? ""
                itemCell.value = .text(msg)
            }
           
        }
        
        //导出
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy_MM_dd_HH:mm_ss"
        let fileName = "\(formatter.string(from: Date()))_质控数据.xlsx"
        let filePath = excelBook.save(fileName)
        print("===========>生成完成\(filePath)")
//        let url = URL(fileURLWithPath: filePath)
        //自动打开该文档
//        NSWorkspace.shared.open(url)
    }
    
    func onWillDown(){
        httpGetData(page: self.pageIndex)
    }
    
    public func getTableHealer()->[String]{
//        return ["档案信息","基本信息","既往史","家族史","遗传病史及残疾情况","生活环境"]
        return Array(tableHeaderNames)
    }
    
    func httpGetData(page:Int){
        print(">>>>>>>>>>>>>>>>>开始查询第\(page)页")
        HttServer.httpGetUserList(pageIndex: page) {re, dataList in
            if re{
                
                DispatchQueue.main.async {
                    var userList:[UserItem] = []
                    for user in dataList{
                        if !user.content.removeAllSapce.isEmpty{
                            let groupMap = user.getGroupMap()
                            for groupName in groupMap.keys{
                                self.tableHeaderNames.insert(groupName)
                            }
                            userList.append(user)
                            self.totalCount += 1
                        }
                    }
                    if !userList.isEmpty{
                        self.dataMap[page] = dataList
                        
                    }
                    print("第\(page)页质控，异常数据共\( self.totalCount)条")
                    //当数据量达到一定史，先生成，再继续查询接收
                    if self.totalCount >= 10000{
                        print("数据达到了\(self.totalCount)，成表格")
                        self.genderExcel()
                        self.totalCount = 0
                        self.dataMap.removeAll()
                    }
                    
                    if !dataList.isEmpty{
                        if self.isStop{
                            print("已暂停。。。。。。")
                            return
                        }
                        self.pageIndex = self.pageIndex + 1
                        httpGetData(page: self.pageIndex)
                    }else{
                        print("------------------批量查询结束，page:\(page)页，错误页码:\(self.errorPage)")
                        self.genderExcel()
                       
                    }
                }
                
               
                
            }else{
                self.errorPage.insert(page)
            }
        }
    }

   
}

#Preview {
    ExportExcelPage()
}
